<template>
  <button
    ref="eggElement"
    class="ak-egg"
    @click="triggerEgg"
    @mousedown="handleMouseDown"
    @mouseenter="handleEggHover"
    @mouseleave="handleEggLeave"
    :class="{ 
      animating: isEggAnimating, 
      running: isRunning, 
      shy: isShy,
      taiko: isTaikoEffect,
      maimai: isMaimaiEffect,
      avoiding: isAvoiding,
      dragging: isDragging
    }"
    :style="{ left: eggLeft + 'px', top: eggTop + 'px' }"
    aria-label="Arknights Egg"
  >
    <img :src="arknightsUrl" alt="Arknights" />
    <!-- 太鼓达人打击波纹效果 -->
    <div class="taiko-ripple" v-if="isTaikoEffect"></div>
    <div class="taiko-ripple delay-1" v-if="isTaikoEffect"></div>
    <div class="taiko-ripple delay-2" v-if="isTaikoEffect"></div>
    
    <!-- maimai 打击效果 -->
    <div class="maimai-star" v-if="isMaimaiEffect"></div>
    <div class="maimai-star delay-1" v-if="isMaimaiEffect"></div>
    <div class="maimai-star delay-2" v-if="isMaimaiEffect"></div>
    <div class="maimai-star delay-3" v-if="isMaimaiEffect"></div>
  </button>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import arknightsUrl from '@/assets/arknights.svg'

// 彩蛋动画 - 使用贝塞尔曲线路径 + 太鼓达人打击感 + 害羞机制
const isEggAnimating = ref(false)
const isRunning = ref(false)
const eggLeft = ref(0)
const eggTop = ref(0)
const eggBusy = ref(false)
const eggElement = ref<HTMLElement | null>(null)

// 拖动相关
const isDragging = ref(false)
const dragStartX = ref(0)
const dragStartY = ref(0)
const dragOffsetX = ref(0)
const dragOffsetY = ref(0)

// 太鼓达人打击感相关
const isTaikoEffect = ref(false)
const isMaimaiEffect = ref(false)

// 害羞机制相关
const isShy = ref(false)
const isAvoiding = ref(false)
const clickCount = ref(0)
const shyTimer = ref<ReturnType<typeof setTimeout> | null>(null)
const avoidTimer = ref<ReturnType<typeof setTimeout> | null>(null)

const setInitialEggPosition = () => {
  const size = 40
  const margin = 14
  eggLeft.value = Math.max(margin, window.innerWidth - size - margin)
  eggTop.value = Math.max(margin, window.innerHeight - size - margin)
}

// 吸边效果：当彩蛋靠近屏幕边缘时自动吸附
const snapToEdge = (x: number, y: number) => {
  const size = 40
  const margin = 14
  const snapThreshold = 100 // 距离边缘100px时开始吸边
  
  let snappedX = x
  let snappedY = y
  
  // 左边缘吸边
  if (x < snapThreshold) {
    snappedX = margin
  }
  // 右边缘吸边
  else if (x > window.innerWidth - size - snapThreshold) {
    snappedX = window.innerWidth - size - margin
  }
  
  // 上边缘吸边
  if (y < snapThreshold) {
    snappedY = margin
  }
  // 下边缘吸边
  else if (y > window.innerHeight - size - snapThreshold) {
    snappedY = window.innerHeight - size - margin
  }
  
  return { x: snappedX, y: snappedY }
}

const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min

// 生成随机贝塞尔曲线控制点
const generateBezierPath = (startX: number, startY: number, endX: number, endY: number) => {
  // 计算距离，用于控制控制点的偏移程度
  const distance = Math.sqrt((endX - startX) ** 2 + (endY - startY) ** 2)
  const controlDistance = Math.min(distance * 0.8, 300) // 控制点最大偏移距离
  
  // 生成两个随机控制点，让路径更加弯曲
  const cp1X = startX + randomInt(-controlDistance, controlDistance)
  const cp1Y = startY + randomInt(-controlDistance, controlDistance)
  const cp2X = endX + randomInt(-controlDistance, controlDistance)
  const cp2Y = endY + randomInt(-controlDistance, controlDistance)
  
  // 确保控制点在屏幕范围内
  const margin = 20
  const clampedCp1X = Math.max(margin, Math.min(window.innerWidth - margin, cp1X))
  const clampedCp1Y = Math.max(margin, Math.min(window.innerHeight - margin, cp1Y))
  const clampedCp2X = Math.max(margin, Math.min(window.innerWidth - margin, cp2X))
  const clampedCp2Y = Math.max(margin, Math.min(window.innerHeight - margin, cp2Y))
  
  return {
    start: { x: startX, y: startY },
    cp1: { x: clampedCp1X, y: clampedCp1Y },
    cp2: { x: clampedCp2X, y: clampedCp2Y },
    end: { x: endX, y: endY }
  }
}

// 沿贝塞尔曲线移动的函数
const moveAlongBezierCurve = (path: { start: { x: number; y: number }; cp1: { x: number; y: number }; cp2: { x: number; y: number }; end: { x: number; y: number } }, duration: number = 600) => {
  const startTime = performance.now()
  
  const animate = (currentTime: number) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 使用三次贝塞尔曲线公式计算当前位置
    const t = progress
    const invT = 1 - t
    
    const x = invT ** 3 * path.start.x + 
              3 * invT ** 2 * t * path.cp1.x + 
              3 * invT * t ** 2 * path.cp2.x + 
              t ** 3 * path.end.x
              
    const y = invT ** 3 * path.start.y + 
              3 * invT ** 2 * t * path.cp1.y + 
              3 * invT * t ** 2 * path.cp2.y + 
              t ** 3 * path.end.y
    
    eggLeft.value = x
    eggTop.value = y
    
    // 添加旋转效果，让彩蛋看起来在"奔跑"
    if (eggElement.value) {
      const rotationAngle = -12 + Math.sin(progress * Math.PI * 4) * 8 // 摆动效果
      eggElement.value.style.transform = `rotate(${rotationAngle}deg) scale(${0.9 + Math.sin(progress * Math.PI * 2) * 0.1})`
    }
    
    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      // 动画结束，重置状态
      isRunning.value = false
      eggBusy.value = false
      if (eggElement.value) {
        eggElement.value.style.transform = ''
      }
    }
  }
  
  requestAnimationFrame(animate)
}

// 害羞机制：鼠标悬停处理
const handleEggHover = () => {
  if (isShy.value && !eggBusy.value) {
    // 害羞状态下，鼠标悬停会自动躲避
    triggerShyAvoidance()
  }
}

const handleEggLeave = () => {
  // 鼠标离开后，如果在害羞状态，延迟返回原位
  if (isShy.value && isAvoiding.value) {
    if (avoidTimer.value) clearTimeout(avoidTimer.value)
    avoidTimer.value = setTimeout(() => {
      returnFromAvoidance()
    }, 1000)
  }
}

const triggerShyAvoidance = () => {
  if (eggBusy.value) return
  eggBusy.value = true
  isAvoiding.value = true

  const shyMessages = [
    '博士...不要这样看着我...',
    '太害羞了，我要躲起来！',
    '不要靠近我啦！',
    '好害羞...快躲开！',
    '博士太热情了...'
  ]

  ElMessage({
    message: shyMessages[randomInt(0, shyMessages.length - 1)],
    type: 'info',
    showClose: true,
    grouping: true,
  })

  // 快速逃到随机位置
  const size = 40
  const margin = 14
  const maxLeft = Math.max(margin, window.innerWidth - size - margin)
  const maxTop = Math.max(margin, window.innerHeight - size - margin)
  const newLeft = randomInt(margin, maxLeft)
  const newTop = randomInt(margin, maxTop)

  const bezierPath = generateBezierPath(eggLeft.value, eggTop.value, newLeft, newTop)
  moveAlongBezierCurve(bezierPath, 500) // 更快的逃跑速度
}

const returnFromAvoidance = () => {
  if (!isShy.value) return
  
  isAvoiding.value = false
  const returnMessages = [
    '博士走开了，可以回来了...',
    '感觉安全了，回到原位',
    '博士不看我了，松了口气'
  ]

  ElMessage({
    message: returnMessages[randomInt(0, returnMessages.length - 1)],
    type: 'success',
    showClose: true,
    grouping: true,
  })
}

const triggerTaikoEffect = () => {
  isTaikoEffect.value = true
  
  // 太鼓达人打击感：震动效果
  if (eggElement.value) {
    eggElement.value.style.animation = 'taikoHit 0.3s ease-out'
    setTimeout(() => {
      if (eggElement.value) {
        eggElement.value.style.animation = ''
      }
    }, 300)
  }

  // 波纹效果持续时间
  setTimeout(() => {
    isTaikoEffect.value = false
  }, 600)
}

const triggerMaimaiEffect = () => {
  isMaimaiEffect.value = true
  
  // maimai 打击感：旋转缩放效果
  if (eggElement.value) {
    eggElement.value.style.animation = 'maimaiSpin 0.4s ease-out'
    setTimeout(() => {
      if (eggElement.value) {
        eggElement.value.style.animation = ''
      }
    }, 400)
  }

  // 星星效果持续时间
  setTimeout(() => {
    isMaimaiEffect.value = false
  }, 700)
}

// 拖动事件处理
const handleMouseDown = (e: MouseEvent) => {
  if (eggBusy.value) return
  
  isDragging.value = true
  dragStartX.value = e.clientX
  dragStartY.value = e.clientY
  dragOffsetX.value = e.clientX - eggLeft.value
  dragOffsetY.value = e.clientY - eggTop.value
  
  // 阻止默认行为
  e.preventDefault()
  
  // 添加拖动样式
  if (eggElement.value) {
    eggElement.value.style.cursor = 'grabbing'
    eggElement.value.style.zIndex = '1200'
  }
}

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return
  
  const newX = e.clientX - dragOffsetX.value
  const newY = e.clientY - dragOffsetY.value
  
  // 应用吸边效果
  const snapped = snapToEdge(newX, newY)
  eggLeft.value = snapped.x
  eggTop.value = snapped.y
}

const handleMouseUp = () => {
  if (!isDragging.value) return
  
  isDragging.value = false
  
  // 恢复样式
  if (eggElement.value) {
    eggElement.value.style.cursor = 'grab'
    eggElement.value.style.zIndex = '1100'
  }
  
  // 最终吸边确认
  const finalPosition = snapToEdge(eggLeft.value, eggTop.value)
  eggLeft.value = finalPosition.x
  eggTop.value = finalPosition.y
}

const triggerEgg = () => {
  if (eggBusy.value || isDragging.value) return
  
  // 增加点击计数
  clickCount.value++

  // 太鼓达人和maimai动画交替出现
  if (clickCount.value % 2 === 1) {
    triggerTaikoEffect()
  } else {
    triggerMaimaiEffect()
  }

  eggBusy.value = true

  // 先受惊抖动/跳动
  isEggAnimating.value = true

  // 根据点击次数显示不同信息，5次后就害羞
  let message = ''
  if (clickCount.value <= 3) {
    // 前3次显示原来的经典提示
    const classicMessages = ['吓！', '博士，别点我！', '救命——']
    message = classicMessages[randomInt(0, classicMessages.length - 1)]
  } else if (clickCount.value === 4) {
    message = '咕噜咕噜跑路！'
  } else if (clickCount.value >= 5) {
    // 5次及以上进入害羞模式
    if (!isShy.value) {
      isShy.value = true
      message = '太多次了...我要害羞了...'
      
      // 设置害羞恢复定时器 (20秒后恢复)
      if (shyTimer.value) clearTimeout(shyTimer.value)
      shyTimer.value = setTimeout(() => {
        isShy.value = false
        isAvoiding.value = false
        clickCount.value = 0
        ElMessage({
          message: '好了，我不害羞了！可以继续点击了~',
          type: 'success',
          showClose: true,
          grouping: true,
        })
      }, 20000)
    } else {
      const veryShyMessages = [
        '不要再点了...太害羞了...',
        '博士...请放过我吧...',
        '我已经很害羞了...',
        '再点我就要消失了！',
        '太鼓和maimai都救不了我了...'
      ]
      message = veryShyMessages[randomInt(0, veryShyMessages.length - 1)]
    }
  }

  ElMessage({
    message: message,
    type: clickCount.value >= 5 ? 'warning' : 'info',
    showClose: true,
    grouping: true,
  })

  // 受惊后沿贝塞尔曲线"逃跑"到随机位置
  setTimeout(() => {
    isEggAnimating.value = false
    isRunning.value = true

    const size = 40
    const margin = 14
    const maxLeft = Math.max(margin, window.innerWidth - size - margin)
    const maxTop = Math.max(margin, window.innerHeight - size - margin)
    const newLeft = randomInt(margin, maxLeft)
    const newTop = randomInt(margin, maxTop)

    // 生成贝塞尔曲线路径并开始动画
    const bezierPath = generateBezierPath(eggLeft.value, eggTop.value, newLeft, newTop)
    const duration = isShy.value ? 600 : 800 // 害羞时移动更快
    moveAlongBezierCurve(bezierPath, duration)
  }, 220)
}

// 窗口大小改变时重新定位
const handleResize = () => {
  setInitialEggPosition()
}

onMounted(() => {
  setInitialEggPosition()
  window.addEventListener('resize', handleResize)
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
  if (shyTimer.value) clearTimeout(shyTimer.value)
  if (avoidTimer.value) clearTimeout(avoidTimer.value)
})
</script>

<style scoped lang="scss">
/* 彩蛋按钮样式与动画 */
.ak-egg {
  position: fixed;
  left: 0;
  top: 0;
  width: 40px;
  height: 40px;
  padding: 6px;
  border-radius: 50%;
  border: none;
  background: rgba(0, 0, 0, 0.35);
  backdrop-filter: blur(6px);
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
  cursor: grab;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition:
    left 0.35s ease,
    top 0.35s ease,
    transform 0.2s ease,
    background 0.2s ease,
    box-shadow 0.3s ease;
  z-index: 1100;
  overflow: visible;
  user-select: none;
}

.ak-egg:active {
  cursor: grabbing;
}

.ak-egg.dragging {
  cursor: grabbing !important;
  transform: scale(1.1);
  box-shadow: 
    0 4px 14px rgba(0, 0, 0, 0.25),
    0 0 30px rgba(255, 255, 255, 0.3);
}

.ak-egg:hover {
  background: rgba(0, 0, 0, 0.45);
}

.ak-egg img {
  width: 100%;
  height: 100%;
  display: block;
  transition: filter 0.3s ease;
}

/* 害羞状态样式 */
.ak-egg.shy {
  background: rgba(255, 182, 193, 0.4) !important;
  box-shadow: 0 4px 14px rgba(255, 105, 180, 0.3);
}

.ak-egg.shy img {
  filter: hue-rotate(30deg) brightness(1.1);
}

.ak-egg.shy:hover {
  background: rgba(255, 182, 193, 0.6) !important;
  transform: scale(0.9);
}

/* 躲避状态 */
.ak-egg.avoiding {
  background: rgba(255, 105, 180, 0.5) !important;
  transform: scale(0.8) rotate(15deg);
}

/* 太鼓达人打击波纹效果 */
.taiko-ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #ff6b6b;
  transform: translate(-50%, -50%);
  animation: taikoRipple 0.6s ease-out forwards;
  pointer-events: none;
}

.taiko-ripple.delay-1 {
  animation-delay: 0.1s;
  border-color: #ffa726;
}

.taiko-ripple.delay-2 {
  animation-delay: 0.2s;
  border-color: #66bb6a;
}

@keyframes taikoRipple {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(3);
    opacity: 0;
  }
}

/* maimai 打击星星效果 */
.maimai-star {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 8px;
  height: 8px;
  background: linear-gradient(45deg, #ff69b4, #00bfff);
  transform: translate(-50%, -50%) rotate(45deg);
  animation: maimaiStar 0.7s ease-out forwards;
  pointer-events: none;
  clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
}

.maimai-star.delay-1 {
  animation-delay: 0.1s;
  background: linear-gradient(45deg, #ffa500, #ff1493);
  animation-name: maimaiStarRotate;
}

.maimai-star.delay-2 {
  animation-delay: 0.2s;
  background: linear-gradient(45deg, #00ff7f, #9370db);
  animation-name: maimaiStarSpiral;
}

.maimai-star.delay-3 {
  animation-delay: 0.3s;
  background: linear-gradient(45deg, #ffff00, #ff4500);
  animation-name: maimaiStarBounce;
}

@keyframes maimaiStar {
  0% {
    transform: translate(-50%, -50%) rotate(45deg) scale(0);
    opacity: 1;
  }
  50% {
    transform: translate(-50%, -50%) rotate(225deg) scale(1.5);
    opacity: 0.8;
  }
  100% {
    transform: translate(-50%, -50%) rotate(405deg) scale(0);
    opacity: 0;
  }
}

@keyframes maimaiStarRotate {
  0% {
    transform: translate(-50%, -50%) rotate(0deg) scale(0) translateX(0);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) rotate(720deg) scale(1) translateX(60px);
    opacity: 0;
  }
}

@keyframes maimaiStarSpiral {
  0% {
    transform: translate(-50%, -50%) rotate(0deg) scale(0) translateX(0) translateY(0);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) rotate(360deg) scale(1) translateX(40px) translateY(-40px);
    opacity: 0;
  }
}

@keyframes maimaiStarBounce {
  0% {
    transform: translate(-50%, -50%) scale(0) translateY(0);
    opacity: 1;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.2) translateY(-30px);
    opacity: 0.9;
  }
  100% {
    transform: translate(-50%, -50%) scale(0.5) translateY(50px);
    opacity: 0;
  }
}

/* 太鼓达人打击震动效果 */
@keyframes taikoHit {
  0% { transform: scale(1) rotate(0deg); }
  25% { transform: scale(1.2) rotate(-2deg); }
  50% { transform: scale(1.1) rotate(2deg); }
  75% { transform: scale(1.15) rotate(-1deg); }
  100% { transform: scale(1) rotate(0deg); }
}

.ak-egg.taiko {
  box-shadow: 
    0 4px 14px rgba(0, 0, 0, 0.25),
    0 0 20px rgba(255, 107, 107, 0.5),
    0 0 40px rgba(255, 167, 38, 0.3);
}

/* maimai 打击旋转效果 */
@keyframes maimaiSpin {
  0% { 
    transform: scale(1) rotate(0deg); 
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
  }
  25% { 
    transform: scale(1.3) rotate(90deg); 
    box-shadow: 
      0 4px 14px rgba(0, 0, 0, 0.25),
      0 0 25px rgba(255, 105, 180, 0.6),
      0 0 50px rgba(0, 191, 255, 0.4);
  }
  50% { 
    transform: scale(0.9) rotate(180deg); 
    box-shadow: 
      0 4px 14px rgba(0, 0, 0, 0.25),
      0 0 30px rgba(255, 215, 0, 0.5),
      0 0 60px rgba(255, 20, 147, 0.3);
  }
  75% { 
    transform: scale(1.1) rotate(270deg); 
    box-shadow: 
      0 4px 14px rgba(0, 0, 0, 0.25),
      0 0 20px rgba(0, 255, 127, 0.6),
      0 0 40px rgba(147, 112, 219, 0.4);
  }
  100% { 
    transform: scale(1) rotate(360deg); 
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
  }
}

.ak-egg.maimai {
  box-shadow: 
    0 4px 14px rgba(0, 0, 0, 0.25),
    0 0 25px rgba(255, 105, 180, 0.5),
    0 0 50px rgba(0, 191, 255, 0.3),
    0 0 75px rgba(255, 215, 0, 0.2);
}

/* 原有动画保持 */
@keyframes akPulse {
  0% {
    transform: scale(1);
  }
  25% {
    transform: scale(1.25);
  }
  55% {
    transform: scale(0.8);
  }
  100% {
    transform: scale(1);
  }
}

.ak-egg.animating {
  animation: akPulse 0.7s ease forwards;
}

.ak-egg.running {
  transform: rotate(-12deg) translateZ(0);
}
</style>
